package cn.matezk.lianlian.tools;

import cn.hutool.json.JSONUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class ExcelQRCodeGenerator {

    public static void main(String[] args) {
        try {
            // 输入和输出文件路径
            String inputFilePath = "C:\\Users\\daolin\\Desktop\\20250809.xlsx";
            String outputFilePath = "C:\\Users\\daolin\\Desktop\\20250809_QR.xlsx";

            // 打开Excel文件
            FileInputStream inputStream = new FileInputStream(inputFilePath);
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表

            // QR code writer
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1); // 设置二维码边距

            // 图片大小
            int qrCodeWidth = 100;
            int qrCodeHeight = 100;

            // 遍历E列，从第1行开始（索引0可能是标题行）
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (row == null) continue;

                Cell pCell = row.getCell(1); // 产品ID
                if (pCell == null || pCell.getCellType() == CellType.BLANK) continue;
                Cell dCell = row.getCell(2); // 设备名称
                if (dCell == null || dCell.getCellType() == CellType.BLANK) continue;

                // 二维码内容
                String content = JSONUtil.createObj()
                        .set("ProductId", getCellValueAsString(pCell))
                        .set("DeviceName", getCellValueAsString(dCell))
                        .toString();

                // 生成二维码
                try {
                    BitMatrix bitMatrix = qrCodeWriter.encode(
                            content,
                            BarcodeFormat.QR_CODE,
                            qrCodeWidth,
                            qrCodeHeight,
                            hints);

                    // 创建图片字节数组
                    BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

                    // 获取或创建F列单元格（第5个索引）
                    Cell fCell = row.getCell(4);
                    if (fCell == null) {
                        fCell = row.createCell(4);
                    }

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write(bufferedImage, "png", baos);

                    // 添加图片到Excel
                    int pictureIdx = workbook.addPicture(baos.toByteArray(), Workbook.PICTURE_TYPE_PNG);

                    // 创建绘图对象
                    Drawing<?> drawing = sheet.createDrawingPatriarch();
                    if (drawing instanceof XSSFDrawing) {
                        // 对于XSSF (xlsx) 文件
                        XSSFClientAnchor anchor = new XSSFClientAnchor(
                                0, 0, 0, 0,
                                fCell.getColumnIndex(), rowNum,
                                fCell.getColumnIndex() + 1, rowNum + 1);
                        anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
                        drawing.createPicture(anchor, pictureIdx);
                    } else {
                        // 对于HSSF (xls) 文件
                        ClientAnchor anchor = workbook.getCreationHelper().createClientAnchor();
                        anchor.setCol1(fCell.getColumnIndex());
                        anchor.setRow1(rowNum);
                        anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
                        drawing.createPicture(anchor, pictureIdx);
                    }

                    // 调整行高以适应二维码
                    row.setHeightInPoints(qrCodeHeight / 0.75F); // 转换像素为点

                } catch (WriterException e) {
                    System.err.println("无法为行 " + (rowNum + 1) + " 生成二维码: " + e.getMessage());
                }
            }

            // 保存修改后的Excel文件
            FileOutputStream outputStream = new FileOutputStream(outputFilePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();
            inputStream.close();

            System.out.println("二维码生成完成，已保存到: " + outputFilePath);

        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    private static String getCellValueAsString(Cell cell) {
        if (cell == null) return null;

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            case BLANK:
                return "";
            default:
                return "";
        }
    }
}